package top.anonyeast.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import top.anonyeast.dao.IPAddressDao;
import top.anonyeast.pojo.IPAddress;
import top.anonyeast.service.IPAddressService;
import top.anonyeast.util.IpUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service("IPAddressService")
public class IPAddressServiceImpl implements IPAddressService {
    @Resource(name = "IPAddressDao")
    private IPAddressDao ipAddressDao;
    @Resource(name = "ipUtils")
    private IpUtils ipUtils;

    /**
     * 插入并获取IP地址列表
     * @param ipAddress
     * @return
     */
    @Override
    public List<IPAddress> insertAndGetIpInfo(String ipAddress,int amount) {
        updateIpInfo(ipAddress,"");//更新ip地址记录
        return getIpRecords(amount);//获取ip地址记录
    }

    /**
     * 插入登陆失败的ip
     * @param ipAddress
     * @param msg
     * @return IP地址对象
     */
    @Override
    public IPAddress insertLoginFailedIpInfo(String ipAddress, String msg){
        return updateIpInfo(ipAddress,msg);
    }

    @Override
    public IPAddress updateIpInfo(String ipAddress,String msg) {
        QueryWrapper<IPAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("outer_ip",ipAddress);
        IPAddress ipInfo = ipAddressDao.selectOne(wrapper);
        //ip地址不存在，插入新的记录
        if (ipInfo == null){
            //获取地理位置
            String location = ipUtils.getLocationByIP(ipAddress);
            //封装IP地址对象并插入数据库
            ipInfo = new IPAddress(ipAddress,location,new Date(),msg);
            ipAddressDao.insert(ipInfo);
        }
        //ip地址存在，则更新已存在的记录
        else {
            ipInfo.setAccessTime(new Date());
            ipInfo.setRemarks(msg);
            ipAddressDao.update(ipInfo,wrapper);
        }
        return ipInfo;
    }

    /**
     * 获取ip地址记录
     * @param amount
     * @return
     */
    @Override
    public List<IPAddress> getIpRecords(int amount) {
        QueryWrapper<IPAddress> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("access_time");
        Page<IPAddress> page = ipAddressDao.selectPage(new Page<>(1, amount),wrapper);
        return page.getRecords();
    }
}
